<template>
  <div class="table-pagination-wrapper">
    <!-- 表格部分 -->
    <el-table
      ref="tableRef"
      :data="tableData"
      :loading="loading"
      :height="height"
      :max-height="maxHeight"
      :stripe="stripe"
      :border="border"
      :size="size"
      :show-header="showHeader"
      :highlight-current-row="highlightCurrentRow"
      :row-class-name="rowClassName"
      :row-style="rowStyle"
      :cell-class-name="cellClassName"
      :cell-style="cellStyle"
      :header-row-class-name="headerRowClassName"
      :header-row-style="headerRowStyle"
      :header-cell-class-name="headerCellClassName"
      :header-cell-style="headerCellStyle"
      @select="handleSelect"
      @select-all="handleSelectAll"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
      @row-dblclick="handleRowDblClick"
      @current-change="handleCurrentChange"
      @sort-change="handleSortChange"
      @header-click="handleHeaderClick"
      @expand-change="handleExpandChange"
    >
      <!-- 多选列 -->
      <el-table-column
        v-if="selection"
        type="selection"
        :width="selectionWidth"
        :fixed="selectionFixed"
        :align="selectionAlign"
      />

      <!-- 序号列 -->
      <el-table-column
        v-if="index"
        type="index"
        :label="indexLabel"
        :width="indexWidth"
        :fixed="indexFixed"
        :align="indexAlign"
        :index="indexMethod"
      />

      <!-- 展开列 -->
      <el-table-column v-if="expand" type="expand" :width="expandWidth" :fixed="expandFixed">
        <template #default="scope">
          <slot name="expand" :row="scope.row" :index="scope.$index" />
        </template>
      </el-table-column>

      <!-- 动态列 -->
      <el-table-column
        v-for="column in columns"
        :key="column.prop || column.label"
        :prop="column.prop"
        :label="column.label"
        :width="column.width"
        :min-width="column.minWidth"
        :fixed="column.fixed"
        :sortable="column.sortable"
        :sort-method="column.sortMethod"
        :sort-by="column.sortBy"
        :sort-orders="column.sortOrders"
        :resizable="column.resizable"
        :formatter="column.formatter"
        :show-overflow-tooltip="column.showOverflowTooltip"
        :align="column.align"
        :header-align="column.headerAlign"
        :class-name="column.className"
        :label-class-name="column.labelClassName"
        :selectable="column.selectable"
        :reserve-selection="column.reserveSelection"
        :filters="column.filters"
        :filter-placement="column.filterPlacement"
        :filter-multiple="column.filterMultiple"
        :filter-method="column.filterMethod"
        :filtered-value="column.filteredValue"
      >
        <!-- 自定义列内容 -->
        <template #default="scope" v-if="column.slot">
          <slot
            :name="column.slot"
            :row="scope.row"
            :column="scope.column"
            :index="scope.$index"
            :value="scope.row[column.prop]"
          />
        </template>

        <!-- 自定义表头 -->
        <template #header="scope" v-if="column.headerSlot">
          <slot :name="column.headerSlot" :column="scope.column" :index="scope.$index" />
        </template>
      </el-table-column>

      <!-- 操作列 -->
      <el-table-column
        v-if="showOperation"
        :label="operationLabel"
        :width="operationWidth"
        :min-width="operationMinWidth"
        :fixed="operationFixed"
        :align="operationAlign"
        :class-name="operationClassName"
      >
        <template #default="scope">
          <slot name="operation" :row="scope.row" :column="scope.column" :index="scope.$index" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器部分 -->
    <el-pagination
      v-if="showPagination"
      v-model:current-page="currentPage"
      v-model:page-size="currentPageSize"
      :page-sizes="pageSizes"
      :pager-count="pagerCount"
      :layout="paginationLayout"
      :total="total"
      :small="paginationSmall"
      :background="paginationBackground"
      :disabled="paginationDisabled"
      :hide-on-single-page="hideOnSinglePage"
      @size-change="handleSizeChange"
      @current-change="handleCurrentPageChange"
      @prev-click="handlePrevClick"
      @next-click="handleNextClick"
      class="pagination-container"
    />
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'

// 定义组件名称
defineOptions({
  name: 'TablePagination',
})

// Props定义
const props = defineProps({
  // 表格数据
  data: {
    type: Array,
    default: () => [],
  },
  // 表格列配置
  columns: {
    type: Array,
    default: () => [],
  },
  // 表格高度
  height: {
    type: [String, Number],
    default: undefined,
  },
  // 表格最大高度
  maxHeight: {
    type: [String, Number],
    default: undefined,
  },
  // 是否显示斑马纹
  stripe: {
    type: Boolean,
    default: false,
  },
  // 是否显示边框
  border: {
    type: Boolean,
    default: false,
  },
  // 表格尺寸
  size: {
    type: String,
    default: 'default',
    validator: (value) => ['large', 'default', 'small'].includes(value),
  },
  // 是否显示表头
  showHeader: {
    type: Boolean,
    default: true,
  },
  // 是否高亮当前行
  highlightCurrentRow: {
    type: Boolean,
    default: false,
  },
  // loading状态
  loading: {
    type: Boolean,
    default: false,
  },

  // 多选相关
  selection: {
    type: Boolean,
    default: false,
  },
  selectionWidth: {
    type: [String, Number],
    default: 55,
  },
  selectionFixed: {
    type: [Boolean, String],
    default: false,
  },
  selectionAlign: {
    type: String,
    default: 'center',
  },

  // 序号相关
  index: {
    type: Boolean,
    default: false,
  },
  indexLabel: {
    type: String,
    default: '#',
  },
  indexWidth: {
    type: [String, Number],
    default: 50,
  },
  indexFixed: {
    type: [Boolean, String],
    default: false,
  },
  indexAlign: {
    type: String,
    default: 'center',
  },
  indexMethod: {
    type: Function,
    default: undefined,
  },

  // 展开行相关
  expand: {
    type: Boolean,
    default: false,
  },
  expandWidth: {
    type: [String, Number],
    default: 50,
  },
  expandFixed: {
    type: [Boolean, String],
    default: false,
  },

  // 操作列相关
  showOperation: {
    type: Boolean,
    default: false,
  },
  operationLabel: {
    type: String,
    default: '操作',
  },
  operationWidth: {
    type: [String, Number],
    default: undefined,
  },
  operationMinWidth: {
    type: [String, Number],
    default: 100,
  },
  operationFixed: {
    type: [Boolean, String],
    default: 'right',
  },
  operationAlign: {
    type: String,
    default: 'center',
  },
  operationClassName: {
    type: String,
    default: '',
  },

  // 样式相关
  rowClassName: {
    type: [String, Function],
    default: '',
  },
  rowStyle: {
    type: [Object, Function],
    default: () => ({}),
  },
  cellClassName: {
    type: [String, Function],
    default: '',
  },
  cellStyle: {
    type: [Object, Function],
    default: () => ({}),
  },
  headerRowClassName: {
    type: [String, Function],
    default: '',
  },
  headerRowStyle: {
    type: [Object, Function],
    default: () => ({}),
  },
  headerCellClassName: {
    type: [String, Function],
    default: '',
  },
  headerCellStyle: {
    type: [Object, Function],
    default: () => ({}),
  },

  // 分页相关
  showPagination: {
    type: Boolean,
    default: true,
  },
  total: {
    type: Number,
    default: 0,
  },
  pageSize: {
    type: Number,
    default: 10,
  },
  currentPageProp: {
    type: Number,
    default: 1,
  },
  pageSizes: {
    type: Array,
    default: () => [10, 20, 50, 100],
  },
  pagerCount: {
    type: Number,
    default: 7,
  },
  paginationLayout: {
    type: String,
    default: 'total, sizes, prev, pager, next, jumper',
  },
  paginationSmall: {
    type: Boolean,
    default: false,
  },
  paginationBackground: {
    type: Boolean,
    default: true,
  },
  paginationDisabled: {
    type: Boolean,
    default: false,
  },
  hideOnSinglePage: {
    type: Boolean,
    default: false,
  },
})

// Emits定义
const emit = defineEmits([
  'update:currentPageProp',
  'update:pageSize',
  'selection-change',
  'select',
  'select-all',
  'row-click',
  'row-dblclick',
  'current-change',
  'sort-change',
  'header-click',
  'expand-change',
  'size-change',
  'current-page-change',
  'prev-click',
  'next-click',
  'page-change',
])

// 响应式数据
const tableRef = ref()
const currentPage = ref(props.currentPageProp)
const currentPageSize = ref(props.pageSize)

// 计算属性
const tableData = computed(() => props.data)

// 监听器
watch(
  () => props.currentPageProp,
  (val) => {
    currentPage.value = val
  },
)

watch(
  () => props.pageSize,
  (val) => {
    currentPageSize.value = val
  },
)

watch(currentPage, (val) => {
  emit('update:currentPageProp', val)
})

watch(currentPageSize, (val) => {
  emit('update:pageSize', val)
})

// 表格事件处理
const handleSelect = (selection, row) => {
  emit('select', selection, row)
}

const handleSelectAll = (selection) => {
  emit('select-all', selection)
}

const handleSelectionChange = (selection) => {
  emit('selection-change', selection)
}

const handleRowClick = (row, column, event) => {
  emit('row-click', row, column, event)
}

const handleRowDblClick = (row, column, event) => {
  emit('row-dblclick', row, column, event)
}

const handleCurrentChange = (currentRow, oldCurrentRow) => {
  emit('current-change', currentRow, oldCurrentRow)
}

const handleSortChange = ({ column, prop, order }) => {
  emit('sort-change', { column, prop, order })
}

const handleHeaderClick = (column, event) => {
  emit('header-click', column, event)
}

const handleExpandChange = (row, expandedRows) => {
  emit('expand-change', row, expandedRows)
}

// 分页事件处理
const handleSizeChange = (size) => {
  currentPageSize.value = size
  emit('size-change', size)
  emit('page-change', {
    currentPage: currentPage.value,
    pageSize: size,
  })
}

const handleCurrentPageChange = (page) => {
  currentPage.value = page
  emit('current-page-change', page)
  emit('page-change', {
    currentPage: page,
    pageSize: currentPageSize.value,
  })
}

const handlePrevClick = (page) => {
  emit('prev-click', page)
}

const handleNextClick = (page) => {
  emit('next-click', page)
}

// 公开的方法
const clearSelection = () => {
  tableRef.value?.clearSelection()
}

const toggleRowSelection = (row, selected) => {
  tableRef.value?.toggleRowSelection(row, selected)
}

const toggleAllSelection = () => {
  tableRef.value?.toggleAllSelection()
}

const setCurrentRow = (row) => {
  tableRef.value?.setCurrentRow(row)
}

const clearSort = () => {
  tableRef.value?.clearSort()
}

const clearFilter = (columnKeys) => {
  tableRef.value?.clearFilter(columnKeys)
}

const doLayout = () => {
  tableRef.value?.doLayout()
}

const sort = (prop, order) => {
  tableRef.value?.sort(prop, order)
}

// 暴露方法给父组件
defineExpose({
  tableRef,
  clearSelection,
  toggleRowSelection,
  toggleAllSelection,
  setCurrentRow,
  clearSort,
  clearFilter,
  doLayout,
  sort,
})
</script>

<style scoped lang="scss">
.table-pagination-wrapper {
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;

    // 响应式设计
    @media (max-width: 768px) {
      justify-content: center;

      :deep(.el-pagination) {
        flex-wrap: wrap;

        .el-pager {
          flex-wrap: wrap;
        }
      }
    }
  }

  // 表格样式优化
  :deep(.el-table) {
    // 表头样式
    .el-table__header-wrapper {
      .el-table__header {
        th {
          background-color: var(--el-fill-color-light);
          color: var(--el-text-color-primary);
          font-weight: 600;
        }
      }
    }

    // 表格行样式
    .el-table__body-wrapper {
      .el-table__row {
        transition: all 0.3s ease;

        &:hover {
          background-color: var(--el-fill-color-lighter);
        }
      }
    }

    // 空状态样式
    .el-table__empty-block {
      .el-table__empty-text {
        color: var(--el-text-color-secondary);
      }
    }
  }

  // Loading样式优化
  :deep(.el-loading-mask) {
    background-color: rgba(255, 255, 255, 0.8);
    backdrop-filter: blur(2px);
  }

  // 操作列按钮样式
  :deep(.el-table__fixed-right) {
    .cell {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 8px;

      .el-button {
        margin: 0;
      }
    }
  }

  // 自定义选择列样式
  :deep(.el-table-column--selection) {
    .cell {
      text-align: center;
    }
  }

  // 自定义序号列样式
  :deep(.el-table__column-resize-proxy) {
    border-color: var(--el-border-color);
  }
}

// 深色主题适配
@media (prefers-color-scheme: dark) {
  .table-pagination-wrapper {
    :deep(.el-table) {
      .el-table__header-wrapper {
        .el-table__header {
          th {
            background-color: var(--el-fill-color-dark);
          }
        }
      }
    }

    :deep(.el-loading-mask) {
      background-color: rgba(0, 0, 0, 0.8);
    }
  }
}

// 紧凑模式样式调整
.table-pagination-wrapper {
  &.el-table--small {
    .pagination-container {
      margin-top: 16px;
    }
  }

  &.el-table--large {
    .pagination-container {
      margin-top: 24px;
    }
  }
}

// 边框模式样式调整
.table-pagination-wrapper {
  :deep(.el-table--border) {
    border-radius: 4px;
    overflow: hidden;

    &::before {
      background-color: var(--el-border-color);
    }

    &::after {
      background-color: var(--el-border-color);
    }
  }
}

// 斑马纹样式调整
.table-pagination-wrapper {
  :deep(.el-table--striped) {
    .el-table__body {
      tr.el-table__row--striped {
        td {
          background-color: var(--el-fill-color-lighter);
        }
      }
    }
  }
}
</style>
